from flask import Blueprint, request, redirect
from common.libs.Helper import ops_renderJSON, ops_renderErrJSON, iPagenation, ops_render
from common.models.thing_list import Thinglist
from common.models.thing_order import ThingOrder
from common.models.thing_project import ThingProject
from application import db, app
from common.libs.DataHelper import getCurrentTime, getCurrentDate
from flask import json
from sqlalchemy import func
from common.models.user import User
import urllib.request
import flask_excel as excel

thing_page = Blueprint("thing_page", __name__)


@thing_page.route("/getproject", methods=["GET", "POST"])
def getProject():
    req = request.values
    city = req['city'] if "city" in req else ""
    a = ThingProject.query.filter_by(city=city).all()
    rts = []
    for item in a:
        temp = dict(project=item.project)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts


@thing_page.route("/getclassone", methods=["GET", "POST"])
def getClassone():
    req = request.values
    city = req['city'] if "city" in req else ""
    a = Thinglist.query.filter_by(city=city).with_entities(Thinglist.classone).distinct().all()
    rts = []
    for item in a:
        temp = dict(classone=item.classone)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts


@thing_page.route("/getclasstwo", methods=["GET", "POST"])
def getClasstwo():
    req = request.values
    city = req['city'] if "city" in req else ""
    classone = req['classone'] if "classone" in req else ""
    a = Thinglist.query.filter_by(city=city, classone=classone).with_entities(Thinglist.classtwo).distinct().all()
    rts = []
    for item in a:
        temp = dict(classtwo=item.classtwo)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts


@thing_page.route("/getclassthree", methods=["GET", "POST"])
def getClassthree():
    req = request.values
    city = req['city'] if "city" in req else ""
    classtwo = req['classtwo'] if "classtwo" in req else ""
    a = Thinglist.query.filter_by(city=city, classtwo=classtwo).with_entities(Thinglist.classthree).distinct().all()
    rts = []
    for item in a:
        temp = dict(classthree=item.classthree)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts


def generateSn(type):
    lastdata = ThingOrder.query.filter_by(type=type).order_by(ThingOrder.id.desc()).first()
    lastdate = lastdata.sn[2:12]
    lastnum = int(lastdata.sn[13:16])
    type1 = type
    if getCurrentDate() == lastdate:
        num = lastnum + 1
        newsn = type1 + str(getCurrentDate()) + "-" + str(num)
        return newsn
    else:
        newsn = type1 + str(getCurrentDate()) + "-" + "1"
        return newsn


@thing_page.route("/thingorder", methods=["GET", "POST"])
def thingorder():
    req = request.values
    content = req['content'] if "content" in req else ""
    uid = req['uid'] if "uid" in req else ""
    type = req['type'] if "type" in req else ""
    city = req['city'] if "city" in req else ""
    project = req['project'] if "project" in req else ""
    content = str(content)
    content1 = json.loads(content)

    if project == "请选择":
        return ops_renderErrJSON(msg="请选择领用项目")

    if len(content) < 1:
        return ops_renderErrJSON(msg="请选择物品")

    if len(uid) < 1:
        return ops_renderErrJSON(msg="非法用户，操作失败")

    else:
        # 生成sn码
        sn = generateSn(type=type)

        for item in content1:
            thing_order = ThingOrder()
            thing_order.sn = sn
            thing_order.classone = item["classone"]
            thing_order.classtwo = item["classtwo"]
            thing_order.classthree = item["classthree"]
            thing_order.num = item["num"]
            thing_order.type = type
            thing_order.project = project
            thing_order.mark = 1
            thing_order.uid = uid
            thing_order.city = city
            thing_order.created_time = thing_order.updated_time = getCurrentTime()
            db.session.add(thing_order)
            db.session.commit()
        return ops_renderJSON(msg="操作成功", code=200)


@thing_page.route("/getthingorderlist", methods=["GET", "POST"])
def getthingorderlist():
    req = request.values
    uid = req['uid'] if "uid" in req else ""
    type = req['type'] if "type" in req else ""

    a = ThingOrder.query.filter(ThingOrder.mark == 1, ThingOrder.uid == uid, ThingOrder.type == type).with_entities(
        ThingOrder.sn).distinct().all()

    # a = Order.query.filter_by(uid=uid,mark=1).all()
    rts = []
    for item in a:
        temp = dict(sn=str(item.sn), url="../thing/thingdetail?sn=" + str(item.sn))
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts


@thing_page.route("/getthingorderdetail", methods=["GET", "POST"])
def getthingorderdetail():
    req = request.values
    sn = req['sn'] if "sn" in req else ""
    a = ThingOrder.query.filter_by(sn=sn, mark=1).all()
    rts = []
    for item in a:
        temp = dict(id=item.id, classone=item.classone, classtwo=item.classtwo, classthree=item.classthree,
                    num=item.num, mark=item.mark)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts


@thing_page.route("/changethingmark", methods=["GET", "POST"])
def changethingmark():
    req = request.values
    id = req['id'] if "id" in req else ""
    mark = req['mark'] if "mark" in req else ""
    type = req['type'] if "type" in req else 1

    a = ThingOrder.query.filter_by(id=id).first()
    city = a.city
    a.mark = mark
    db.session.commit()
    if type == 1:
        return ops_renderJSON(msg="状态变更成功")
    else:
        return redirect('thingadmin?city=' + city)




@thing_page.route("/changethingallmark", methods=["GET", "POST"])
def changethingallmark():
    req = request.values
    sn = req['sn'] if "sn" in req else ""
    mark = req['mark'] if "mark" in req else ""
    a = ThingOrder.query.filter_by(sn=sn).all()
    for item in a:
        item.mark = mark
        db.session.commit()
    return ops_renderJSON(msg="领用状态变更成功")


# 扫码验证出库二维码
@thing_page.route("/adminchange", methods=["GET", "POST"])
def adminchange():
    req = request.values
    sn = req['sn'] if "sn" in req else ""
    city = req['city'] if "city" in req else ""
    a = ThingOrder.query.filter_by(sn=sn).all()
    for item in a:
        item.mark = 2
        db.session.commit()
        thing = Thinglist.query.filter_by(classtwo=item.classtwo, classthree=item.classthree, city=city).first()
        storage = thing.num - item.num
        thing.num = storage
        db.session.commit()

    return ops_renderJSON(msg="领用状态变更成功")


# 扫码验证入库二维码
@thing_page.route("/adminrkchange", methods=["GET", "POST"])
def adminrkchange():
    req = request.values
    sn = req['sn'] if "sn" in req else ""
    city = req['city'] if "city" in req else ""
    a = ThingOrder.query.filter_by(sn=sn).all()
    for item in a:
        item.mark = 2
        db.session.commit()
        thing = Thinglist.query.filter_by(classtwo=item.classtwo, classthree=item.classthree, city=city).first()
        storage = thing.num + item.num
        thing.num = storage
        db.session.commit()

    return ops_renderJSON(msg="领用状态变更成功")


def placeNone(a):
    a = a
    if a == "None":
        b = 0
    else:
        b = a
    return b


# @thing_page.route("/getthingstorage", methods=["GET", "POST"])
# def getthingstorage():
#     req = request.values
#     city = req['city'] if "city" in req else ""
#     city = city
#     thinglist = Thinglist.query.filter_by(city=city).all()
#     rts = []
#     for item in thinglist:
#         ordernum = str(ThingOrder.query.filter_by(classtwo=item.classtwo, classthree=item.classthree).with_entities(
#             func.sum(ThingOrder.num)).scalar())
#         ordernum = placeNone(ordernum)
#         ordernum = int(ordernum)
#         num = item.num - ordernum
#
#         temp = dict(classone=item.classone, classtwo=item.classtwo, classthree=item.classthree, num=num)
#         rts.append(temp)
#     return json.dumps(rts, ensure_ascii=False)

@thing_page.route("/getthingstorage", methods=["GET", "POST"])
def getthingstorage():
    req = request.values
    city = req['city'] if "city" in req else ""
    classone = req['classone'] if "classone" in req else ""
    # city = city
    # classone=classone
    thinglist = Thinglist.query.filter(Thinglist.city == city, Thinglist.classone == classone,
                                       Thinglist.classone != "请选择", Thinglist.classtwo != "请选择",
                                       Thinglist.classthree != "请选择").all()
    rts = []
    for item in thinglist:
        temp = dict(classone=item.classone, classtwo=item.classtwo, classthree=item.classthree, num=item.num)
        rts.append(temp)
    return json.dumps(rts, ensure_ascii=False)


def pagessearch(seal, stime, etime, city):
    req = request.values
    stime = stime
    etime = etime
    page = 1
    if 'p' in req and req['p']:
        page = int(req['p'])

    page_params = {
        'total_count': seal.count(),
        "page_size": 14,
        'page': page,
        'url': "/thing/thingsearch?starttime=" + stime + "&endtime=" + etime + "&city=" + city,
    }
    pages = iPagenation(page_params)
    # -1 - 30,30 - 60 ,60 - 90
    offset = (page - 1) * page_params['page_size']
    limit = page * page_params['page_size']
    seal = seal[offset:limit]

    return pages, seal


#
#
def pagesadmin(seal, city):
    req = request.values
    page = 1
    if 'p' in req and req['p']:
        page = int(req['p'])

    page_params = {
        'total_count': seal.count(),
        "page_size": 8,
        'page': page,
        'url': "/thing/thingadmin?city=" + city,
    }
    pages = iPagenation(page_params)
    # -1 - 30,30 - 60 ,60 - 90
    offset = (page - 1) * page_params['page_size']
    limit = page * page_params['page_size']
    seal = seal[offset:limit]

    return pages, seal


@thing_page.route('/thingadmin', methods=['GET', 'POST'])
def thingadmin():
    city = request.args.get('city')
    thingdoing = ThingOrder.query.filter_by(city=city, mark=1, type="LY").order_by(
        ThingOrder.created_time.desc())
    pages1, thingdoing = pagesadmin(thingdoing, city)
    return ops_render("/admin/thingadmin.html", { "pages1": pages1,"thingdoing": thingdoing,"t":1})


@thing_page.route('/thingsearch', methods=['GET', 'POST'])
def thingsearch():
    starttime = request.args.get('starttime')
    endtime = request.args.get('endtime')
    city = request.args.get('city')
    t= request.args.get('t')

    thingdone = ThingOrder.query.filter(ThingOrder.type == "LY",
                                        ThingOrder.updated_time.between(starttime, endtime), ThingOrder.city == city,
                                        ThingOrder.mark == 2).order_by(
        ThingOrder.updated_time.desc())

    rk = ThingOrder.query.filter(ThingOrder.type == "RK",
                                 ThingOrder.updated_time.between(starttime, endtime), ThingOrder.city == city,
                                 ThingOrder.mark == 2).order_by(
        ThingOrder.updated_time.desc())
    pages2, thingdone = pagessearch(thingdone, starttime, endtime, city)
    pages3, rk = pagessearch(rk, starttime, endtime, city)

    return ops_render("/admin/thingadmin.html",
                      { "pages2": pages2, "pages3": pages3, "rk": rk,
                       "thingdone": thingdone, "stime": starttime,
                       "etime": endtime,"t":t})


# 汇总Excel数据
# def make_excel_list(data, fields, column_names):
#     list_data = []
#
#     list_data.append(column_names)
#     for item in data:
#         tmp = []
#         for fi in fields:
#             tmp.append(getattr(item,fi))
#         list_data.append(tmp)
#         print(list_data)
#     return list_data

def make_excel_listly(data, column_names):
    list_data = []
    list_data.append(column_names)
    for item in data:
        tmp = [item.sn, item.classone, item.classtwo, item.classthree, item.num, item.creater.nickname, item.creater.company, item.creater.department, item.project ,item.created_time]
        list_data.append(tmp)
    return list_data

def make_excel_listrk(data, column_names):
    list_data = []
    list_data.append(column_names)
    for item in data:
        tmp = [item.sn, item.classone, item.classtwo, item.classthree, item.num, item.creater.nickname, item.creater.company,item.created_time]
        list_data.append(tmp)
    return list_data


excel.init_excel(app)


@thing_page.route("/exportly", methods=['GET'])
def export_recordsly():
    starttime = request.args.get('starttime')
    endtime = request.args.get('endtime')
    city = request.args.get('city')

    query_sets = ThingOrder.query.filter(
        ThingOrder.created_time.between(starttime, endtime), ThingOrder.type == "LY", ThingOrder.mark == 2,ThingOrder.city==city).order_by(
        ThingOrder.created_time.desc()).all()
    column_names = ['领用单号', '品类', '名称', '型号', '数量', '领用人', '领用公司', '领用部门', '领用项目',"申请时间"]
    # fields = ['sn', 'classone', 'classtwo', 'classthree', 'num', 'creater.nickname','creater.company', 'creater.department', 'project', 'created_time']
    excel_data = make_excel_listly(query_sets,column_names)

    # app.logger.info(excel_data)

    return excel.make_response_from_array(excel_data, file_type='xls',
                                          file_name=starttime+"至"+endtime+city+"耗材领用信息",
                                          sheet_name='领用信息')

@thing_page.route("/exportrk", methods=['GET'])
def export_recordsrk():
    starttime = request.args.get('starttime')
    endtime = request.args.get('endtime')
    city = request.args.get('city')

    query_sets = ThingOrder.query.filter(
        ThingOrder.created_time.between(starttime, endtime), ThingOrder.type == "RK", ThingOrder.mark == 2,ThingOrder.city==city).order_by(
        ThingOrder.created_time.desc()).all()
    column_names = ['入库单号', '品类', '名称', '型号', '数量', '送货人', '送货公司', "送货时间"]
    excel_data = make_excel_listrk(query_sets, column_names)

    # app.logger.info(excel_data)

    return excel.make_response_from_array(excel_data, file_type='xls',
                                          file_name=starttime+"至"+endtime+city+"耗材入库信息",
                                          sheet_name='入库信息')
